package com.mazong.serversecaa.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Slf4j
@Component
public class MyAccessDecisionManager implements AccessDecisionManager {

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        if(collection == null || collection.size() <= 0) {
            log.info("不需要权限");
            return;
        }

        //-- 验证用户权限
        String needRole;
        for(ConfigAttribute configAttribute:collection) {

            //-- 获取需要权限
            needRole = configAttribute.getAttribute();

            //-- 用户有什么权限
            for(GrantedAuthority grantedAuthority: authentication.getAuthorities()) {
                log.info("needRole={},userRole={}", needRole, grantedAuthority.getAuthority());
                if(needRole.trim().equals(grantedAuthority.getAuthority().trim())) {
                    log.info("权限没问题");
                    return;
                }
            }
        }

        //--
        throw new AccessDeniedException("没有访问当前页面的权限");
    }
}
